﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class ClientDbController : Controller
    {
        System.Data.SQLiteProvider.SQLiteConfigService config;

        System.Data.SQLiteProvider.SQLiteSqlService sqlService;

        Infrastructure.Data.Client.SQLite.ClientDbService clientDbService;

        Application.Admin.Sight.IOpenSightService openSightService;

        Application.Admin.Tour.IOpenTourService openTourService;

        Infrastructure.Crosscutting.Authorize.IUserService userService;

        public ClientDbController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            System.Data.SQLiteProvider.SQLiteConfigService con,
            System.Data.SQLiteProvider.SQLiteSqlService sql,
            Infrastructure.Data.Client.SQLite.ClientDbService clientDb,
            Application.Admin.Sight.IOpenSightService openSight,
            Application.Admin.Tour.IOpenTourService openTour,
            Infrastructure.Crosscutting.Authorize.IUserService user)
        {
            if (con == null)
            {
                throw new ArgumentNullException("config is null");
            }
            if (sql == null)
            {
                throw new ArgumentNullException("sqlService is null");
            }
            if (clientDb == null)
            {
                throw new ArgumentNullException("clientDbService is null");
            }
            if (openSight == null)
            {
                throw new ArgumentNullException("openSightService is null");
            }
            if (openTour == null)
            {
                throw new ArgumentNullException("openTourService is null");
            }
            if (user == null)
            {
                throw new ArgumentNullException("userService is null");
            }
            config = con;
            sqlService = sql;
            sqlService.ConnectionStringBuilder = config.ConnectionStringBuilder;
            clientDbService = clientDb;
            openSightService = openSight;
            openTourService = openTour;
            userService = user;
        }

        public ActionResult Index()
        {
            var currentUser = Session[Infrastructure.Crosscutting.Comm.Service.ConstService.SessionNameCurrentUser] as
               Domain.Entity.User;
            if (currentUser != null && currentUser.Id > 0)
            {
                return View();
            }
            else
            {
                return RedirectToAction("denied", "error");
            }
        }

        public ActionResult DownClientDb(string userName, string pwd)
        {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(pwd)
                && userName.ToLower().CompareTo("imapopenuser") == 0)
            {
                pwd = Infrastructure.Crosscutting.Comm.Service.StringService.Tomd5(pwd);
                if (userService.GetList().Where(e => e.UserName == userName && e.Pwd == pwd).Any())
                {
                    var fs = new System.IO.FileStream(config.DbFilePhyPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    return new FileStreamResult(fs, "application/octet-stream");
                }
                else
                {
                    return new EmptyResult();
                }
            }
            else
            {
                return new EmptyResult();
            }
        }

        [HttpPost]
        public JsonResult UpdateClientDb()
        {
            var res = false;
            var message = "";
            var currentUser = Session[Infrastructure.Crosscutting.Comm.Service.ConstService.SessionNameCurrentUser] as
                Domain.Entity.User;
            if (currentUser != null && currentUser.Id > 0)
            {
                //先清空所有数据，
                sqlService.DeleteTableAllData(clientDbService.Table.Select(d => d.Name).ToList());
                //再添加数据
                //1.image
                //2.line
                //3.poi
                if (this.AddClientImageData() && this.AddClientLineData() && this.AddClientPointData())
                {
                    res = true;
                }
                else
                {
                    message = "系统未完成更新客户端数据库，你可以再尝试几次";
                }
            }
            else
            {
                message = "没有权限";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Version()
        {
            var res = false;
            var message = "";
            var version = System.IO.File.GetLastWriteTime(config.DbFilePhyPath);
            res = true;
            return Json(new { success = res, message = message, version = version.ToString("yyyy-MM-dd HH:mm:ss.fff") }, JsonRequestBehavior.AllowGet);
        }

        #region util

        protected bool AddClientPointData()
        {
            var res = false;
            var data = openSightService.GetAllOpenSightWithOneOpenPicBySortNum().AsQueryable();
            var sql = Infrastructure.Data.Client.SQLite.ClientBuilderSqlService.BuilderSql(data);
            res = sqlService.ExecuteSqlTran(sql);
            return res;
        }

        protected bool AddClientLineData()
        {
            var res = false;
            var lineId = openTourService.GetAllTour().Select(d => d.Id);
            var data = new List<Application.Admin.Dto.OpenTourDetailDto>();
            foreach (var item in lineId)
            {
                var temp = openTourService.GetTourDetailByTourId(item);
                if (temp != null)
                {
                    data.Add(temp);
                }
            }
            var sql = Infrastructure.Data.Client.SQLite.ClientBuilderSqlService.BuilderSql(data.AsQueryable());
            res = sqlService.ExecuteSqlTran(sql);
            return res;
        }

        protected bool AddClientImageData()
        {
            var res = false;
            var image = openSightService.GetAllSightAllOpenPic();
            var sql = Infrastructure.Data.Client.SQLite.ClientBuilderSqlService.BuilderSql(image.AsQueryable());
            res = sqlService.ExecuteSqlTran(sql);
            return res;
        }

        #endregion
    }
}
